// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/format_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/network_image_load/load_image.dart';
import 'package:yt_devops/components/app_permission/permission_widget.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/pages/site/site_overview/site_overview_controller.dart';
import 'package:yt_devops/pages/site/site_overview/site_overview_model.dart';
import 'package:yt_devops/pages/site/widgets/statistics_itme_widget.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'component/site_ennergy_flow.dart';

class SiteOverviewView extends GetView<SiteOverviewController> {
  SiteOverviewView({Key? key}) : super(key: key);
  @override
  final controller = Get.put(SiteOverviewController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SiteOverviewController>(
      init: controller,
      builder: (controller) {
        return Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage(ImageAssets.siteOverviewBg))),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBarWidget.withRightActions(controller.siteName,
                backgroundColor: Colors.transparent,
                actions: [
                  PermissionWidget(
                    permissionStringList: [
                      PermissionConstant.homeSiteManageAlarm
                    ],
                    mode: AuthorityModeType.include,
                    child: GestureDetector(
                        onTap: () => controller.goAlarmPage(),
                        child: Stack(alignment: Alignment.center, children: [
                          Container(
                            alignment: Alignment.centerRight,
                            padding: EdgeInsets.only(right: 16),
                            // color: Colors.green,
                            width: 80,
                            height: 40,
                            child: SizedBox(
                              height: 44,
                              child: Image.asset(
                                ImageAssets.headerAlarm,
                                color: Colour.black,
                                width: 20,
                                height: 20,
                              ),
                            ),
                          ),
                          Positioned(
                            top: 12,
                            right: 8,
                            // right: controller.alarmSum > 10 ? 10.w : 14.w,
                            child: Visibility(
                              visible: controller.alarmSum != 0,
                              child: Container(
                                alignment: Alignment.center,
                                height: 16,
                                width: 16,
                                // 一个值的时候保持圆形故宽度使用h
                                decoration: BoxDecoration(
                                  color: Colors.red,
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(8),
                                  ),
                                  border: Border.all(
                                    color: Colors.white,
                                  ),
                                ),
                                child: Text(
                                  controller.alarmSum > 100
                                      ? "99"
                                      : controller.alarmSum.toString(),
                                  textAlign: TextAlign.start,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 10,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ])),
                  )
                ]),
            body: Container(
              margin: EdgeInsets.only(bottom: 10),
              child: _generateView(),
            ),
          ),
        );
      },
    );
  }

  Widget _generateView() {
    return PermissionWidget(
        permissionStringList: [PermissionConstant.homeSiteManageOverviewDetail],
        child: SmartRefresher(
            controller: controller.refreshController,
            enablePullDown: true,
            enablePullUp: false,
            header: ListTips.classicHeader,
            onRefresh: () => controller.onRefresh(),
            child: ListView(
              physics: const AlwaysScrollableScrollPhysics(),
              children: [
                Gaps.vGap14,
                deviceDataWidget(),
                Container(
                  padding: EdgeInsets.only(top: 11, left: 16.w, right: 16.w),
                  child: Row(
                    children: [
                      SizedBox(
                          width: 24.w,
                          height: 24.w,
                          child: SvgPicture.asset(controller.getWeatherSvgMap(
                              controller.weatherModel.weather))),
                      SizedBox(
                        width: 8.w,
                      ),
                      Text('${controller.weatherModel.temperature ?? ''}℃',
                          softWrap: true,
                          style: TextStyles.f18.mediumStyle.dinStyle),
                      Spacer(),
                      Visibility(
                        visible: controller.monitorIsOpen,
                        child: GestureDetector(
                          onTap: () => controller.jumpApp(),
                          child: Image.asset(
                            'assets/images/site_video_open.png',
                            height: 60,
                            width: 60,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                KeepAliveWrapper(
                  SiteEnergyFlowWidget(
                    controller.siteId,
                    energyType:
                        PowerStationType.getType(controller.energyOptions),
                  ),
                ),
                if (controller.energyOptions
                        ?.contains(SiteEnergyOptionType.photovolatic.value) ==
                    true) //光伏
                  siteStaticWidget(
                      title: ResKey.siteOverviewPhotovoltaic.tr,
                      iconUrl: ImageAssets.iconStatisticPv,
                      data: controller.pvStatistics,
                      headLinearGradient: LinearGradient(colors: [
                        Color(0xFFFFEFD9),
                        Color(0xFFFFFFFF),
                      ])),
                if (controller.energyOptions
                        ?.contains(SiteEnergyOptionType.storage.value) ==
                    true) //储能
                  siteStaticWidget(
                      title: ResKey.siteOverviewStoredEnergy.tr,
                      iconUrl: ImageAssets.iconStatisticEss,
                      data: controller.essStatistics,
                      headLinearGradient: LinearGradient(colors: [
                        Color(0xFFD1E5FF),
                        Color(0xFFFFFFFF),
                      ]),
                      isStorage: true),
                if (!(controller.energyOptions
                        ?.contains(SiteEnergyOptionType.charge.value) ==
                    true))
                  siteStaticWidget(
                      //负载
                      title: ResKey.deviceLoad.tr,
                      data: controller.loadStatistics,
                      iconUrl: ImageAssets.iconStatisticLoad,
                      headLinearGradient: LinearGradient(colors: [
                        Color(0xFFD1F6FF),
                        Color(0xFFFFFFFF),
                      ]))
                else
                  siteStaticWidget(
                      //充电桩
                      title: ResKey.deviceLoad.tr,
                      iconUrl: ImageAssets.iconStatisticLoad,
                      data: controller.chargeStatistics,
                      headLinearGradient: LinearGradient(colors: [
                        Color(0xFFD1F6FF),
                        Color(0xFFFFFFFF),
                      ])),
              ],
            )));
  }

  Widget siteStaticWidget(
      {required String? title,
      required String iconUrl,
      required List<StatisticsItemModel> data,
      LinearGradient? headLinearGradient,
      isStorage = false //是否为储能
      }) {
    List<Widget> cols = [];
    var j = 0;
    while (j + 2 <= data.length) {
      List<Widget> rows = [];
      rows.addAll([
        siteStaticItemWidget(data[j]),
        Container(
          height: 42,
          width: 0.5,
          color: Colour.dividerColor,
        ),
        siteStaticItemWidget(data[j + 1]),
      ]);
      j = j + 2;
      cols.add(
        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: rows),
      );
    }

    if (j == data.length - 1) {
      cols.add(
        Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [siteStaticItemWidget(data[data.length - 1]), Spacer()]),
      );
    }

    return Column(
      children: [
        Container(
          margin: EdgeInsets.fromLTRB(16.w, 16, 16.w, 0),
          decoration: BoxDecoration(
              color: Colour.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
              boxShadow: [
                BoxShadow(
                    offset: Offset(0, 2),
                    blurRadius: 12,
                    color: Colors.black.withOpacity(0.08)),
              ]),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                padding: EdgeInsets.only(left: 16.w),
                height: 48,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10.w),
                        topRight: Radius.circular(10.w)),
                    gradient: headLinearGradient),
                child: Row(children: [
                  Image.asset(
                    iconUrl,
                    width: 24.w,
                  ),
                  Gaps.hGap5,
                  Text(title!.tr, style: TextStyles.f18.mediumStyle),
                ]),
              ),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: isStorage && controller.esUnitList.length >= 2
                      ? null
                      : BorderRadius.only(
                          bottomLeft: Radius.circular(10),
                          bottomRight: Radius.circular(10)),
                ),
                child: ListView.separated(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) => cols[index],
                  separatorBuilder: (context, index) => Container(
                    height: 0.5,
                    color: Colour.dividerColor,
                    margin: EdgeInsets.only(left: 16.w, right: 16.w),
                  ),
                  itemCount: cols.length,
                ),
              ),
              if (isStorage &&
                  controller.isMore &&
                  controller.esUnitList.isNotEmpty)
                Container(
                  // padding: EdgeInsets.only(top: 10),
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                  child: Column(children: _getEsList()),
                ),
              if (isStorage &&
                  controller.esUnitList.length >= 2 &&
                  !controller.isMore)
                Container(
                    height: 0.5,
                    margin: EdgeInsets.only(left: 16.w, right: 16.w),
                    color: Colour.dividerColor),
              if (isStorage && controller.esUnitList.length >= 2)
                MyGestureDetector(
                  onTap: () {
                    controller.isMore = !controller.isMore;
                    controller.update();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(10),
                          bottomRight: Radius.circular(10)),
                    ),
                    padding: EdgeInsets.only(
                        bottom: 10, top: 10, right: 100, left: 100),
                    width: double.infinity,
                    child: Image.asset(
                      controller.isMore
                          ? 'assets/images/es_arrow_up.png'
                          : 'assets/images/es_arrow_down.png',
                      width: 18,
                      height: 18,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  List<Widget> _getEsList() {
    List<Widget> list = [];
    for (int i = 0; i < controller.esUnitList.length; i++) {
      var map = controller.esUnitList[i];
      list.add(individualEsDeviceDataWidget(map, margin: i == 0 ? 0 : 16));
    }
    return list;
  }

  Widget siteStaticItemWidget(StatisticsItemModel item) {
    return Container(
        height: 74,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
        ),
        child: esItemWidget(
            item.name.toString(), item.value.toString(), item.unit.toString()));
  }

  ///储能单个设备的视图
  Widget individualEsDeviceDataWidget(Map map, {double margin = 16}) {
    Log.d('map===' + map.toString());
    return Container(
      margin: EdgeInsets.only(top: margin, left: 16.w, right: 16.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          border: Border(
              bottom: BorderSide(width: 0.5, color: Colour.borderColor),
              left: BorderSide(width: 0.5, color: Colour.borderColor),
              right: BorderSide(width: 0.5, color: Colour.borderColor))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            height: 40,
            decoration: BoxDecoration(
              color: Colour.backgroundColor,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
            ),
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 16.w),
            child: Text(
              map['groupName'] ?? '',
              style: TextStyle(
                  fontSize: 16, fontWeight: FontWeight.w500, height: 1.2),
            ),
          ),
          Row(
            children: [
              esItemWidget(
                controller.getStoredEnergyData({})[0].name.toString(),
                map['chargeDay'] != null ? map['chargeDay'].toString() : '--',
                controller.getStoredEnergyData({})[0].unit.toString(),
              ),
              Container(
                height: 42,
                width: 0.5,
                color: Colour.dividerColor,
              ),
              esItemWidget(
                controller.getStoredEnergyData({})[1].name.toString(),
                map['dischargeDay'] != null
                    ? map['dischargeDay'].toString()
                    : '--',
                controller.getStoredEnergyData({})[1].unit.toString(),
              )
            ],
          ),
          Container(
              height: 0.5,
              margin: EdgeInsets.only(left: 16.w, right: 16.w),
              color: Colour.dividerColor),
          Row(
            children: [
              esItemWidget(
                controller.getStoredEnergyData({})[2].name.toString(),
                map['chargeTotal'] != null
                    ? map['chargeTotal'].toString()
                    : '--',
                controller.getStoredEnergyData({})[2].unit.toString(),
              ),
              Container(
                height: 42,
                width: 0.5,
                color: Colour.dividerColor,
              ),
              esItemWidget(
                  controller.getStoredEnergyData({})[3].name.toString(),
                  map['dischargeTotal'] != null
                      ? map['dischargeTotal'].toString()
                      : '--',
                  controller.getStoredEnergyData({})[3].unit.toString()),
            ],
          ),
          Container(
              height: 0.5,
              margin: EdgeInsets.only(left: 16.w, right: 16.w),
              color: Colour.dividerColor),
          Row(
            children: [
              esItemWidget(
                  controller.getStoredEnergyData({})[4].name.toString(),
                  map['gainDay'] != null ? map['gainDay'].toString() : '--',
                  controller.getStoredEnergyData({})[4].unit.toString()),
              Container(
                height: 42,
                width: 0.5,
                color: Colour.dividerColor,
              ),
              esItemWidget(
                controller.getStoredEnergyData({})[5].name.toString(),
                map['gainTotal'] != null ? map['gainTotal'].toString() : '--',
                controller.getStoredEnergyData({})[5].unit.toString(),
              ),
            ],
          ),
          // Container(
          //     height: 0.5,
          //     margin: EdgeInsets.only(left: 16.w, right: 16.w),
          //     color: Colour.dividerColor),
        ],
      ),
    );
  }

  Widget esItemWidget(
    String title,
    String numValue,
    String unit,
  ) {
    var realValue = '--';
    var unitStr = unit;
    if (unit == '元' || unit == '¥') {
      unitStr = controller.monetaryUnitName;
    }
    if (numValue != null && numValue.isNotEmpty && numValue != '--') {
      realValue = FormatUtil.commaSeparatedDigits(num.parse(numValue));
    }
    if ((unit.toString() == '¥' ||
            unit.toString() == '\$' ||
            unit.toString() == '€') &&
        num.parse(numValue) < 0) {
      unitStr = '-$unit';
      realValue = FormatUtil.commaSeparatedDigits(num.parse(numValue).abs());
    }

    // Log.d('unit===' + unitStr);
    // Log.d('controller.monetaryUnitName===' + controller.monetaryUnitName);
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 5),
      height: 66,
      width: (ScreenUtil().screenWidth - 34.w - 32.w) * 0.5,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20), color: Colors.white),
      alignment: Alignment.center,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Gaps.vGap14,
          (unitStr.contains('¥') ||
                  unitStr.contains('€') ||
                  unitStr.contains('\$'))
              ? Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                          text: unitStr,
                          style: ytTextStyle(
                            fontSize: 11,
                            color: Colour.mainTextColor,
                          )),
                      TextSpan(
                        text: realValue,
                        style: dinTextStyle(
                            fontSize: 16,
                            color: Colour.mainTextColor,
                            fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                )
              : Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: realValue,
                        style: dinTextStyle(
                            fontSize: 16,
                            color: Colour.mainTextColor,
                            fontWeight: FontWeight.w500),
                      ),
                      TextSpan(
                          text: unitStr,
                          style: ytTextStyle(
                            fontSize: 11,
                            color: Colour.mainTextColor,
                          )),
                    ],
                  ),
                ),
          Gaps.vGap4,
          Text(
            title,
            maxLines: 2,
            textAlign: TextAlign.center,
            style: ytTextStyle(
                fontSize: 12,
                color: Colour.labelTextColor,
                fontWeight: FontWeight.normal,
                height: 1),
          ),
        ],
      ),
    );
  }

  Widget deviceDataWidget() {
    return controller.deviceCountInfo == null
        ? Gaps.empty
        : Container(
            height: 42,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: Color(0xFF567FA7).withOpacity(0.1),
              borderRadius: BorderRadius.circular(10.w),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                deviceItemWidget(
                    title: ResKey.siteRunningDays.tr,
                    value: controller.operationDays ?? 0,
                    unit: ''),
                deviceItemWidget(
                    title: ResKey.deviceAllCount.tr,
                    value: controller.deviceCountInfo!.totalCount,
                    unit: ''),
                deviceItemWidget(
                    title: ResKey.deviceOnlineCount.tr,
                    value: controller.deviceCountInfo!.onlineCount,
                    unit: ''),
              ],
            ),
          );
  }

  Widget deviceItemWidget(
      {required String title, required int value, required String unit}) {
    return Text.rich(
      TextSpan(
          text: '$title：',
          style: TextStyles.styleWith(12.sp, color: Colour.otherTextColor),
          children: [
            TextSpan(
                text: value.toString(),
                style:
                    dinTextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500)),
            TextSpan(text: unit)
          ]),
    );
  }
}
